#include "connection.h"

#include <QtGlobal>
#include <QFile>
#include <QDebug>

#include <unistd.h>

Connection::Connection(quint32 uid, int fd[], QObject *parent)
    : QObject{parent}
{
    qDebug() << "child connection setup" << uid << fd[0] << fd[1];
    QFile file;
    bool ok = file.open(fd[1], QFile::ReadWrite);
    qDebug() << ok << file.errorString();
    m_localSocket = new QLocalSocket(this);
    m_localSocket->setSocketDescriptor(fd[1]);

    qDebug() << m_localSocket->readAll();

    close(fd[0]);
    connect(m_localSocket, &QLocalSocket::readyRead, this, &Connection::onSocketReadyRead);
}

void Connection::writeMessage(const QByteArray &buffer)
{
    m_localSocket->write(buffer);
}

void Connection::onSocketReadyRead()
{
    auto data = m_localSocket->readAll();
    if (!qgetenv("debug").isEmpty()) {
        qDebug() << "service receive message from index framework" << data;
    }
    auto msgs = data.split('\0');
    for (auto msg : msgs) {
        emit messageReceived(msg);
    }
}
